package com.twt.recruit.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;

/**
 * @author LiBo
 * @date 2021年11月09日 0:20
 */
public class JwtTokenUtils {
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    private static final String SECRET = "d2df9g";
    private static final String ISS = "2f4h5tge";

    // 过期时间是3600秒，既是1个小时
    private static final long EXPIRATION = 3600L;

    // 选择了记住我之后的过期时间为7天
    private static final long EXPIRATION_REMEMBER = 604800L;



    private static final String ROLE_CLAIMS = "rol";

    private static final String CLUB_CLAIMS = "club";


    // 创建token，uid+role
    public static String createToken(String userNumber, Integer clubId, String role, boolean isRememberMe) {
        long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        HashMap<String, Object> map = new HashMap<>();
        map.put(ROLE_CLAIMS, role);
        map.put(CLUB_CLAIMS, clubId);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setClaims(map)
                .setIssuer(ISS)
                .setSubject(userNumber)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .compact();
    }

    // 从token中获取用户名
    public static String getUserNumber(String token){
        return getTokenBody(token).getSubject();
    }

    public static String getUserRole(String token){
        return (String) getTokenBody(token).get(ROLE_CLAIMS);
    }

    public static Integer getUserClub(String token){
        return (Integer) getTokenBody(token).get(CLUB_CLAIMS);
    }

    public static String getUserNumberHttp(String tokenHeader){

        String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");
        return JwtTokenUtils.getUserNumber(token);
    }
    public static String getRoleHttp(String tokenHeader){
        String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");
        return JwtTokenUtils.getUserRole(token);
    }

    public static Integer getClubHttp(String tokenHeader){
        String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");
        return JwtTokenUtils.getUserClub(token);
    }

    // 是否已过期
    public static boolean isExpiration(String token){
        try {
            return getTokenBody(token).getExpiration().before(new Date());
        } catch (ExpiredJwtException e) {
            return true;
        }
    }

    private static Claims getTokenBody(String token){
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }
}
